//
//  ZYIndexMainVC.m
//  YiLin
//
//  Created by Zyark on 2018/5/29.
//  Copyright © 2018年 Zyark. All rights reserved.
//

#import "ZYIndexMainVC.h"
#import "ZYDeviceDetailVC.h"
#import "ZYHomeHeaderView.h"
#import "DeviceCommunicate.pbobjc.h"
#import "RHSocketService.h"
#import "ZYHome.h"
#import "ZYHouse.h"
#import "ZYIndexDeviceView.h"
#import "ZYIndexMiddleView.h"
#import "ZYDevice.h"
#import "ZYHouseViewModel.h"
#import "ZYDeviceViewModel.h"
#import "ZYIndexDataViewModel.h"
#import "KxMenu.h"
#import "EBDropdownListView.h"
#import "UINavigationController+FDFullscreenPopGesture.h"

@interface ZYIndexMainVC ()<ZYIndexDeviceViewDelegate>
@property(nonatomic,strong) ZYHomeHeaderView *headerView;
@property(nonatomic,strong) UIImageView *bottomImageView;
//@property(nonatomic,strong) ZYIndexMiddleView *middleView;
@property(nonatomic,strong) UIScrollView *scrollView;
@property(nonatomic,strong) UIView *bgView;
@property(nonatomic,strong) NSArray *homeArray;
@property(nonatomic,strong) NSMutableArray<NSArray *> *deviceArray;
@property(nonatomic,strong) NSMutableArray<ZYIndexDeviceView *> *deviceViewArray;
@property(nonatomic,strong) ZYHouseViewModel *houseViewModel;
/**
 左侧菜单组
 */
@property(nonatomic,strong) NSArray *leftMenuItemArray;

/**
 右侧菜单组
 */
@property(nonatomic,strong) NSArray *rightMenuItemArray;

@property(nonatomic,assign) BOOL isShowRightMenu;


/**
 左侧下拉选择
 */
@property(nonatomic,strong) EBDropdownListView *leftListView;

/**
 当前住宅id
 */
@property(nonatomic,assign) NSInteger houseId;

/**
 获取设备信息
 */
@property(nonatomic,strong) ZYDeviceViewModel *deviceViewModel;

/**
 当前住宅信息
 */
@property(nonatomic,strong) ZYHome *home;

/**
 获取顶部数据
 */
@property(nonatomic,strong) ZYIndexDataViewModel *homeViewModel;

/**当前选中设备*/
@property(nonatomic,strong) ZYDevice *currentDevice;

@property(nonatomic,assign) BOOL isSelectDevice;
@end

@implementation ZYIndexMainVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.fd_interactivePopDisabled = YES;
    self.tabBarController.tabBar.hidden = NO;
    _leftListView.hidden = NO;
    [self setupRightButton];
    [self.houseViewModel.indexHouseCommand execute:nil];//获取住宅列表
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.fd_interactivePopDisabled = NO;
}

-(void)setup{
    [self.view.layer addSublayer:[ZYUtils setGradualChangingColor:self.view fromHexColorStr:kMainColorStartColorHexString toHexColorStr:kMainColorEndColorHexString locations:@[@0.3, @1.0]]];
    [self setupView];
    [self bindView];
}

//初始化右侧导航栏
-(void)setupRightButton{
    UIButton *button = [[UIButton alloc] init];
    button.frame = CGRectMake(0, 0, 80, 25);
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button.titleLabel setFont:[UIFont systemFontOfSize:14]];
    self.navigationItem.rightBarButtonItem = barButtonItem;
    [button addTarget:self action:@selector(showRightMenu:) forControlEvents:UIControlEventTouchUpInside];
    button.layer.borderColor = [UIColor whiteColor].CGColor;
    button.layer.borderWidth = 1;
    button.layer.cornerRadius = 3;
    button.layer.masksToBounds = YES;
    ZYChangeLanguage *language = [ZYChangeLanguage sharedZYChangeLanguage];
    if([[language userLanguage] hasPrefix:@"en"]){
        [button setTitle:[language getStringByKey:LC_ENGLISH] forState:UIControlStateNormal];
    }else{
        [button setTitle:[language getStringByKey:LC_CHINESE] forState:UIControlStateNormal];
    }
}

-(void)setupLeftListView{
    _leftListView = [[EBDropdownListView alloc] init];
    _leftListView.size = CGSizeMake(90, 35);
    _leftListView.backgroundColor = [UIColor clearColor];
    _leftListView.font = [UIFont systemFontOfSize:20];
    _leftListView.textColor = kLabelColor;
    _leftListView.selectTextColor = [UIColor whiteColor];
    _leftListView.arrowImgName = @"ic_home_main_select";
    @weakify(self);
    [_leftListView setDropdownListViewSelectedBlock:^(EBDropdownListView *dropdownListView) {
        @strongify(self);
        //选中一个住宅
        NSInteger index = dropdownListView.selectedIndex;
        ZYHouse *house = [self.homeArray objectAtIndex:index];
        if(house){
            [ZYConfig setHouseId:[NSString stringWithFormat:@"%ld",(long)house.houseId]];
            self.houseId = house.houseId;
            [ZYConfig setIsAtHome:house.userIn];
            [self.deviceViewModel.deviceListCommand execute:nil];//获取住宅设备列表
//            self.homeViewModel.houseId = self.houseId;
//            [self.homeViewModel.dataCommand execute:nil];//获取顶部数据
        }
    }];
    [self countWidth:_leftListView];
}

-(void)countWidth:(EBDropdownListView *)dropdownListView{
    NSString *longestItem = @"";
    for (EBDropdownListItem *item in dropdownListView.dataSource) {
        if ([item.itemName length] > [longestItem length]) {
            longestItem = item.itemName;
        }
    }
    NSDictionary *attributes = @{NSFontAttributeName:dropdownListView.font,};
    CGSize textSize = [longestItem boundingRectWithSize:CGSizeMake(ZYSCREEN_W * 0.75, dropdownListView.height)
                                                  options:NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;
    CGFloat width = textSize.width + 40;
    if([dropdownListView.dataSource count] == 0){
        width = 20;
    }
    if(width > ZYSCREEN_W / 2){
        width = ZYSCREEN_W / 2;
    }
    _leftListView.width = width;
    dropdownListView.width = width;
    if(ZYiOS_11_OR_LATER){
        [_leftListView removeFromSuperview];
        self.navigationItem.hidesBackButton = YES;
        [self.navigationController.navigationBar addSubview:_leftListView];
        _leftListView.left = 15;
    }else{
        UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_leftListView];
        self.navigationItem.leftBarButtonItems = @[barButtonItem];
    }
}

-(void)changeLanguage{
    [super changeLanguage];
    [_headerView setupTitle];
//    [_middleView setupTitle];
    for (ZYIndexDeviceView *view in _deviceViewArray) {
        [view setupTitle];
    }
    [self setupRightMenuItem];
    [self setupRightButton];
    [self setupDeviceView];
}

-(void)setupView{
//    _headerView = [[ZYHomeHeaderView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W, ZYSCREEN_H * 0.34)];
//    [self.view addSubview:_headerView];
    
//    _middleView = [[ZYIndexMiddleView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W, ZYSCREEN_H * 0.13)];
//    [self.view addSubview:_middleView];
//    _middleView.top = _headerView.bottom;
//    _middleView.centerX = self.view.centerX;
    
//    CGRect rectOfNavigationbar = self.navigationController.navigationBar.frame;
//    _bottomImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W, ZYSCREEN_H  - CGRectGetHeight(rectOfNavigationbar))];
//    _bottomImageView.image = [UIImage imageNamed:@"ic_index_main_bottom_bg"];
//    [self.view addSubview:_bottomImageView];
//    _bottomImageView.top = _headerView.bottom;
//    _bottomImageView.centerX = self.view.centerX;
    
//    _scrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
//    _scrollView.scrollEnabled = YES;
//    _scrollView.contentSize = CGSizeMake(0, CGFLOAT_MIN);
//    [self.view addSubview:_scrollView];
    
    CGFloat height = self.view.height - SafeAreaTopHeight - SafeAreaBottomHeight - self.tabBarController.tabBar.height;
    _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, ZYSCREEN_W, height)];
    _bgView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_bgView];
    
    [self setupDeviceView];
    [self setupRightMenuItem];
    [self setupLeftListView];
}

-(void)setupRightMenuItem{
    ZYChangeLanguage *language = [[ZYChangeLanguage alloc] init];
    _rightMenuItemArray =
    @[
      [KxMenuItem menuItem:[language getStringByKey:LC_ENGLISH]
                     image:nil
                    target:self
                    action:@selector(changeLanguageByEnglish)],
      [KxMenuItem menuItem:[language getStringByKey:LC_CHINESE]
                     image:nil
                    target:self
                    action:@selector(changeLanguageByChinese)]];
}



-(void)bindView{
    @weakify(self);
    //设备socket地址 获取后重新连接socket
    [[[self.deviceViewModel.deviceSocketCommand executionSignals] switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        self.isSelectDevice = YES;
        [self reconnectWithIp:x macAddress:self.deviceViewModel.mac isDisconnect:YES];//重新连接socket
    }];
    [self.deviceViewModel.deviceSocketCommand.errors subscribeNext:^(id x) {
        @strongify(self);
        [ZYBasicHelper handleErrorMessaeWithError:x message:[NSErrorHelper handleErrorMessage:x] controller:self];
    }];
    
    [[[self.houseViewModel.indexHouseCommand executionSignals] switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        self.homeArray = x;
        NSMutableArray *dataSource = [NSMutableArray arrayWithCapacity:[x count]];
        for (ZYHouse *house in x) {
            EBDropdownListItem *item = [[EBDropdownListItem alloc] initWithItem:[NSString stringWithFormat:@"%ld",(long)house.houseId] itemName:house.name];
            [dataSource addObject:item];
        }
        self.leftListView.dataSource = dataSource;
        NSString *houseId = [ZYConfig houseId];
        BOOL isAtHome = NO;
        if(NULLString(houseId) || [houseId isEqualToString:@"0"]){
            ZYHouse *house = [self.homeArray firstObject];
            [ZYConfig setHouseId:[NSString stringWithFormat:@"%ld",(long)house.houseId]];
            self.houseId = house.houseId;
            isAtHome = house.userIn;
        }else{
            NSInteger index = 0;
            for (ZYHouse *house in self.homeArray) {
                if(house.houseId == [houseId integerValue]){
                    isAtHome = house.userIn;
                    break;
                }
                index ++;
            }
            self.leftListView.selectedIndex = index;
            self.houseId = [houseId unsignedIntegerValue];
        }
        [self.deviceViewModel.deviceListCommand execute:nil];//获取住宅设备列表
//        self.homeViewModel.houseId = self.houseId;
//        [self.homeViewModel.dataCommand execute:nil];//获取顶部数据
        [self countWidth:self.leftListView];//重新计算宽度
        [ZYConfig setIsAtHome:isAtHome];
    }];
    
    [self.houseViewModel.indexHouseCommand.errors subscribeNext:^(id x) {
        @strongify(self);
        NSString *houseId = [ZYConfig houseId];
        BOOL isAtHome = NO;
        if(NULLString(houseId) || [houseId isEqualToString:@"0"]){//当获取的住宅列表为空时
            self.homeArray = [NSArray array];
            self.leftListView.dataSource = [NSArray array];
            [self countWidth:self.leftListView];//重新计算宽度
            self.deviceArray = [NSMutableArray array];
            self.deviceViewArray = [NSMutableArray array];
            self.home = nil;
            self.headerView.home = nil;
            [self setupData:[NSArray array]];
            [ZYConfig setIsAtHome:isAtHome];
        }
        [ZYBasicHelper handleErrorMessaeWithError:x message:[NSErrorHelper handleErrorMessage:x] controller:self];
    }];
    
    //获取该住宅设备列表
    [[[self.deviceViewModel.deviceListCommand executionSignals] switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        [self setupData:x];
    }];
    [self.deviceViewModel.deviceListCommand.errors subscribeNext:^(id x) {
        @strongify(self);
        [ZYBasicHelper handleErrorMessaeWithError:x message:[NSErrorHelper handleErrorMessage:x] controller:self];
    }];
    
    //获取顶部数据
    [self.homeViewModel.dataCommand.errors subscribeNext:^(id x) {
        @strongify(self);
        [ZYBasicHelper handleErrorMessaeWithError:x message:[NSErrorHelper handleErrorMessage:x] controller:self];
    }];
    [[[self.homeViewModel.dataCommand executionSignals] switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        self.home = x;
        self.headerView.home = x;
    }];
}

//-(void)setupData:(NSArray *)deviceArray{
//    NSMutableArray *livingRoomDeviceArray = [NSMutableArray array];
//    NSMutableArray *bedRoomDeviceArray = [NSMutableArray array];
//    NSMutableArray *childDeviceArray = [NSMutableArray array];
//    for (ZYDevice *device in deviceArray) {
//        switch (device.roomType) {
//            case ZYHomeRoomTypeLivingRoom:
//                [livingRoomDeviceArray addObject:device];
//                break;
//            case ZYHomeRoomTypeBedroom:
//                [bedRoomDeviceArray addObject:device];
//                break;
//            case ZYHomeRoomTypeChildrenRoom:
//                [childDeviceArray addObject:device];
//                break;
//            default:
//                break;
//        }
//    }
//    self.deviceArray = [[NSMutableArray alloc] init];
//    [self.deviceArray addObject:livingRoomDeviceArray];
//    [self.deviceArray addObject:bedRoomDeviceArray];
//    [self.deviceArray addObject:childDeviceArray];
//    [self setupDeviceView];
//}

//设备列表
-(void)setupData:(NSArray *)deviceArray{
    self.deviceArray = [[NSMutableArray alloc] init];
    [self.deviceArray addObject:deviceArray];
    [self setupDeviceView];
}

-(void)setupDeviceView{
    _deviceViewArray = nil;
    _deviceViewArray = [NSMutableArray array];
    [_bgView removeAllSubviews];
    int count = 0;
    CGFloat height = 0;
    CGFloat top = 0;
    for (NSArray *array in self.deviceArray) {
        if([array count] == 0){
            count ++;
            continue;
        }
        ZYIndexDeviceView *view = [[ZYIndexDeviceView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W, _bgView.height) withRoomType:count withDeviceArray:array];
        view.delegate = self;
        [_bgView addSubview:view];
        view.top = top + 10;
        top =view.top + view.height;
        height = view.bottom + 15 + _headerView.bottom;
        count ++;
    }
    
    NSLog(@"height:%.0f",height);
//    _scrollView.contentSize = CGSizeMake(0, height);
}

#pragma mark - Event
/**
 显示右边菜单
 @param button 按钮
 */
-(void)showRightMenu:(UIButton *)button{
    _isShowRightMenu = !_isShowRightMenu;
    if(_isShowRightMenu){
        [KxMenu setTintColor:[UIColor whiteColor]];
        [KxMenu setTitleFont:[UIFont systemFontOfSize:14]];
        [KxMenu showMenuInView:self.view fromRect:[self.navigationController.view convertRect:button.frame fromView:button.superview] menuItems:_rightMenuItemArray withOptions:[self setupMenuConfig]];
    }else{
        [KxMenu dismissMenu];
    }
}

/**
 切换英文
 */
-(void)changeLanguageByEnglish{
    _isShowRightMenu = !_isShowRightMenu;
    [super setLanguage:@"en"];
}
/**
 切换中文
 */
-(void)changeLanguageByChinese{
    _isShowRightMenu = !_isShowRightMenu;
    [super setLanguage:@"zh-Hans"];
}

/**
 配置菜单参数
 
 @return OptionalConfiguration
 */
-(OptionalConfiguration)setupMenuConfig{
    Color textColor;
    textColor.R = 102/255.0;
    textColor.G = 102/255.0;
    textColor.B = 102/255.0;
    Color menuBackgroundColor;
    menuBackgroundColor.R = 1;
    menuBackgroundColor.G = 1;
    menuBackgroundColor.B = 1;
    OptionalConfiguration config;
    config.arrowSize = 0;//指示箭头大小
    config.marginXSpacing = 5;  //MenuItem左右边距
    config.marginYSpacing = 8;  //MenuItem上下边距
    config.intervalSpacing = 10;//MenuItemImage与MenuItemTitle的间距
    config.menuCornerRadius = 5;//菜单圆角半径
    config.maskToBackground = NO;//是否添加覆盖在原View上的半透明遮罩
    config.hasSeperatorLine = NO;
    config.textColor = textColor; //menuItem字体颜色
    config.menuBackgroundColor = menuBackgroundColor;
    config.hasSeperatorLine = NO;
    return config;
}

#pragma mark - ZYIndexDeviceViewDelegate
-(void)indexDeviceView:(ZYIndexDeviceView *)indexDeviceView didSelectDevice:(ZYDevice *)device{
    //选中某个设备
    _currentDevice = device;
//     self.deviceViewModel.mac = _currentDevice.mac;
//    [self.deviceViewModel.deviceSocketCommand execute:nil];//获取设备socket地址
    ZYDeviceDetailVC *vc = [[ZYDeviceDetailVC alloc] init];
    vc.currentDevice = _currentDevice;
    vc.title = _currentDevice.name;
    vc.hidesBottomBarWhenPushed = YES;
    _leftListView.hidden = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

//-(void)connectSocketSuccess:(NSNotification *)notif{
//    if (self.isViewLoaded && self.view.window) {
//        [self getDeviceData];//获取设备信息
//    }
//}

-(void)getDeviceData{
    if(!_currentDevice){
        return;
    }
    device_communicate *message = [[device_communicate alloc] init];
    RHSocketPacketRequest *req = [[RHSocketPacketRequest alloc] init];
    message.module = 100;
    message.cmd = 1;
    message.sid = [ZYConfig loginToken];
    message.userId = [ZYConfig userId];
    message.macAddress = _currentDevice.mac;
    //    NSSet *data = [NSSet setWithArray:@[@"powerStatus",@"lockStatus",@"pannelModel"
    //                                        ,@"loadStatus",@"roomTemperatureC2",@"environmentAlarm1"
    //                                        ,@"deviceAlarm1",@"controlFlag",@"workModel",@"windSpeed",@"windPannelModel"]];
    message.jsonStr = @"";
    NSLog(@"json:%@",message.jsonStr);
    req.object = [message data];
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationSocketPacketRequest object:req];
}

//-(void)receiveMsgData:(device_communicate *)data{
//
//    if(!NULLString(data.jsonStr)){
//        NSData *jsonData = [data.jsonStr dataUsingEncoding:NSUTF8StringEncoding];
//        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData: jsonData options:NSJSONReadingAllowFragments error:nil];
//        NSString *code = [dict objectForKey:@"code"];
//        NSLog(@"module:%d",data.module);
//        NSLog(@"cmd:%d",data.cmd);
//        if([code integerValue] == 200){
//            ZYDevice *device = [ZYDevice modelWithJSON:[dict objectForKey:@"result"]];
//            NSDictionary *result = [dict objectForKey:@"result"];
//            NSDictionary *roomTemperatureC2 = [result objectForKey:@"roomTemperatureC2"];
//            NSDictionary *setTemperatureC2 = [result objectForKey:@"setTemperatureC2"];
//            if(roomTemperatureC2){
//                _currentDevice.isConnect = YES;
//                _currentDevice.isLock = device.isLock;
//                _currentDevice.isOpen = device.isOpen;
//                _currentDevice.curveType = device.curveType;
//                _currentDevice.roomTemperature = device.roomTemperature;
//                _currentDevice.workModeType = device.workModeType;
//                _currentDevice.vsModeType = device.vsModeType;
//                _currentDevice.windSpeedType = device.windSpeedType;
//                _currentDevice.pmExponent = device.pmExponent;
//                _currentDevice.outPmExponent = device.outPmExponent;
//                _currentDevice.humidity = device.humidity;
//                _currentDevice.outHumidity = device.outHumidity;
//                _currentDevice.outTemperature = device.outTemperature;
//                _currentDevice.formaldehyde = device.formaldehyde;
//                _currentDevice.tvoc = device.tvoc;
//                _currentDevice.carbonDioxide = device.carbonDioxide;
//                _currentDevice.roomTemperature = [NSString stringWithFormat:@"%@",[roomTemperatureC2 objectForKey:@"value"]];
//                _currentDevice.windSpeedIn100 = device.windSpeedIn100;
//                if([[result allKeys] containsObject:@"windSpeedIn100"]){
//                    _currentDevice.isNewVS = YES;
//                }else{
//                    _currentDevice.isNewVS = NO;
//                }
//                CGFloat temperature = [[setTemperatureC2 objectForKey:@"value"] doubleValue];
//                _currentDevice.temperature = [NSString stringWithFormat:@"%.0f",roundf(temperature)];
//            }
//        }
//    }
//    if(self.isSelectDevice){
//        ZYDeviceDetailVC *vc = [[ZYDeviceDetailVC alloc] init];
//        vc.currentDevice = _currentDevice;
//        vc.title = _currentDevice.name;
//        vc.hidesBottomBarWhenPushed = YES;
//        _leftListView.hidden = YES;
//        [self.navigationController pushViewController:vc animated:YES];
//    }
//    self.isSelectDevice = NO;
//}

#pragma mark - Getter
-(ZYHouseViewModel *)houseViewModel{
    if(!_houseViewModel){
        _houseViewModel = [[ZYHouseViewModel alloc] init];
    }
    return _houseViewModel;
}

-(ZYDeviceViewModel *)deviceViewModel{
    if(!_deviceViewModel){
        _deviceViewModel = [[ZYDeviceViewModel alloc] init];
    }
    return _deviceViewModel;
}

-(ZYIndexDataViewModel *)homeViewModel{
    if(!_homeViewModel){
        _homeViewModel = [[ZYIndexDataViewModel alloc] init];
    }
    return _homeViewModel;
}

@end
